package com.itlong.cloud.controller.wechat;

import com.itlong.cloud.POJO.DTO.common.AccessToken;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.iottp.IWeChatMessageServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.WechatMenuUtil;
import com.itlong.cloud.utils.words.WechatMessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
* 微信后台控制器
*
* @author Jiaqi.X
* @version 1.0
* @date 2016-12-21 17:13:31
*/
@Controller
@RequestMapping("/wechat")
public class WechatMessageController extends BaseController implements PlatformConstants {
    @Autowired
    IWeChatMessageServiceClient iWeChatMessageServiceClient;

    @Autowired
    RedisService redisService;

    /**
     * <p/>
     *      微信自动回复
     * <p/>
     * @param request
     * @param response
     * @param signature     微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp     时间戳
     * @param nonce         随机数
     * @param echostr       随机字符串
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/message")
    public void returnNews(HttpServletRequest request,HttpServletResponse response,
                           String signature,String timestamp,String nonce,String echostr) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        if("GET".equals(request.getMethod())) {
            //如果是get请求进行本机与微信服务器握手
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (WechatMessageUtil.checkSignature(signature, timestamp, nonce)) {
                System.out.println("验证签名成功");
                out.print(echostr);
            }
        }else {
            // xml请求解析
            Map<String, String> requestMap = WechatMessageUtil.parseXml(request);
            String result = iWeChatMessageServiceClient.processRequestForNews(requestMap);
            out.print(result);
        }
        out.close();
        out=null;
    }

    /**
     * <p/>
     *      创建菜单
     * <p/>
     * @return
     */
    @RequestMapping(value="/menu/createMenu",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String createMenu() throws IOException {
        //获取微信accessToken
        String accessToken=redisService.get("wechatAccessToken");
        boolean result= WechatMenuUtil.createMenu(JsonUtil.toJSON(WechatMenuUtil.getMenu()), accessToken);
        return result ? "创建菜单成功":"error";
    }

    /**
     * 将字符串转成unicode
     * @param str 待转字符串
     * @return unicode字符串
     */
    public String convert(String str)
    {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++)
        {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>>8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }
}
